package cn.zhxu.toys.msg;

import cn.zhxu.okhttps.HttpResult;
import cn.zhxu.okhttps.HttpUtils;
import cn.zhxu.data.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;

/**
 * 聚合信息发送器
 * 
 * @author Troy.Zhou
 * 
 * @since 1.0.2
 * 
 */
public class JuheMsgSender extends AbstractMsgSender {

	static Logger log = LoggerFactory.getLogger(JuheMsgSender.class);
	
	public static String DEFAULT_ENDPOINT = "http://v.juhe.cn/sms/send";

	
	private String endpoint = DEFAULT_ENDPOINT;
	
	private String appId;


	@Override
	public void init(Map<String, String> params) {
		String endpoint = params.get("endpoint");
		String appId = params.get("appId");
		if (appId == null) {
			throw new MsgSenderInitException("缺少参数：appId");
		}
		if (endpoint != null) {
			this.endpoint = endpoint;
		}
		this.appId = appId;
	}

	@Override
	public boolean send(String phone, MsgTemplate template, String... tmplArgs) {
		Map<String, String> params = new HashMap<>();
		params.put("mobile", phone);
		params.put("tpl_id", template.getTmplValue());
		params.put("key", appId);
		if (tmplArgs != null) {
			String[] argNames = template.getTmplArgs();
			if (tmplArgs.length > 0 && (argNames == null || argNames.length < tmplArgs.length)) {
				throw new RuntimeException("MsgTemplate tmplArgs not match: " + Arrays.toString(argNames) + " to " + Arrays.toString(tmplArgs));
			}
			StringBuilder sb = new StringBuilder();
			for (int index = 0; index < tmplArgs.length; index ++) {
				sb.append("#").append(argNames[index]).append("#=").append(tmplArgs[index]);
				if (index < tmplArgs.length - 1) {
					sb.append("&");
				}
			}
			params.put("tpl_value", sb.toString());
		}
		params.put("dtype", "json");
		try {
			return send(phone, params);
		} catch (Exception e) {
			throw new RuntimeException("聚合信息发送异常：", e);
		}
	}

	private boolean send(String phone, Map<String, String> params) {
		log.info("send params [" + phone + "] = " + params);
		HttpResult result = HttpUtils.sync(endpoint).addBodyPara(params).post();
		if (!result.isSuccessful()) {
			log.error("聚合短信返回状态码错误：" + result.getStatus());
			return false;
		}
		Mapper json = result.getBody().toMapper();
		if (json.getString("error_code").equals("0")) {
			return true;
		} else {
			log.error("发送信息不成功：{}", json);
			return false;
		}
	}
	
	public String getEndpoint() {
		return endpoint;
	}

	public void setEndpoint(String endpoint) {
		this.endpoint = endpoint;
	}

	public void setAppId(String appId) {
		this.appId = appId;
	}
	
	public String getAppId() {
		return appId;
	}
	
}
